<?php

namespace services\rbac;

use api\modules\v1\forms\member\MemberForm;
use common\components\Service;
use common\models\member\Member;
use common\models\rbac\UserRole;
use services\api\AccessTokenService;
use services\member\MemberDepartmentService;
use Yii;

/**
 * Class UserRoleService
 * @package services\rbac
 */
class UserRoleService extends Service
{
    /**
     * 获取用户查询绑定角色Ids
     * @param int $memberId
     * @return array
     */
    public static function getUserRoleEnableIds(int $memberId): array
    {
        $roleIds = self::getUserRoleIds($memberId);
        $roleList = RoleService::getEnableListByIds($roleIds);
        return $roleList ? array_column($roleList, 'id') : [];
    }

    /**
     * 获取角色查询绑定用户Ids
     * @param int|array $roleId
     * @return array
     */
    public static function getRoleUserIds($roleId): array
    {
        return UserRole::find()
            ->select(['member_id'])
            ->where([
                'role_id' => $roleId
            ])
            ->column();
    }

    /**
     * 获取用户查询绑定角色Ids
     * @param int|array $memberIds
     * @return array
     */
    public static function getUserRoleIds($memberIds): array
    {
        return UserRole::find()
            ->select(['role_id'])
            ->where([
                'member_id' => $memberIds
            ])
            ->column();
    }

    /**
     * 获取绑定角色人员IDs
     * @param int $roleId
     * @return array
     */
    public static function deleteUserRole(int $roleId): array
    {
        $memberIds = self::getRoleUserIds($roleId);
        UserRole::deleteAll(['role_id' => $roleId]);
        return $memberIds;
    }

    /**
     * 编辑项目
     * @param Member $member
     * @param MemberForm $model
     * @return void
     * @throws \Exception
     */
    public static function editModel(Member $member, MemberForm $model): void
    {
        if ($model->getScenario() == 'edit') {
            UserRole::deleteAll(['member_id' => $member->id]);
        }
        $data = [];
        $roles = $model->getRoleList();
        foreach ($roles as $role) {
            $data[] = [
                $member->id,
                $role->id,
                Yii::$app->user->identity->member_id,
                time(),
                time(),
            ];
        }
        $data && Yii::$app->db->createCommand()->batchInsert(
            UserRole::tableName(),
            ['member_id', 'role_id', 'operate_id', 'created_at', 'updated_at'],
            $data
        )->execute();
    }

    /**
     * 根据角色强制退出绑定用户
     * @param int|array $roleIds
     * @return void
     */
    public static function clearRoleMemberToken($roleIds): void
    {
        if (empty($roleIds)) {
            return;
        }
        // 3.绑定角色人员强制退出登录
        $memberIds = self::getRoleUserIds($roleIds);
        $memberIds && AccessTokenService::clearMemeberToken($memberIds);
    }

    /**
     * 部门角色、默认角色变动【删除人员绑定对应角色】
     * @param int|array $departmentIds
     * @param int|array $roleIds
     * @return void
     */
    public static function deleteDepartmentRole($departmentIds, $roleIds): void
    {
        if (empty($roleIds)) {
            return;
        }
        $memberIds = MemberDepartmentService::getMemberIdsByDepartmentId($departmentIds);
        if (empty($memberIds)) {
            return;
        }
        $memberIds = array_values(array_intersect($memberIds, self::getRoleUserIds($roleIds)));
        UserRole::deleteAll(['member_id' => $memberIds, 'role_id' => $roleIds]);
        AccessTokenService::clearMemeberToken($memberIds);
    }

    /**
     * 删除部门【清空部门下人员角色】
     * @param int|array $departmentIds
     * @param int|array $roleIds
     * @return void
     */
    public static function deleteDepartment($departmentIds): void
    {
        $memberIds = MemberDepartmentService::getMemberIdsByDepartmentId($departmentIds);
        if (empty($memberIds)) {
            return;
        }
        UserRole::deleteAll(['member_id' => $memberIds, 'role_id' => $roleIds]);
        AccessTokenService::clearMemeberToken($memberIds);
    }
}
